/*
 * @Author: 刘经标 2604132672@qq.com
 * @Date: 2025-04-15 10:17:43
 * @LastEditors: 刘经标 2604132672@qq.com
 * @LastEditTime: 2025-05-09 17:12:29
 * @FilePath: /ai-assistant-frontend/src/components/ChatInput.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Avatar, Box, TextField, IconButton, Paper, Typography } from '@mui/material';
import { Send, Face as UserIcon, SmartToy as BotIcon, Close, Image as ImageIcon, LocationOn } from '@mui/icons-material';
import { useState, useRef } from 'react';
import { EmojiPickerComponent } from './EmojiPicker';
import { ImageUpload } from './ImageUpload';
import { getRegeo } from '../services/amap';

interface ChatInputProps {
  onSend: (content: string, image?: File, location?: { latitude: number; longitude: number; address: string; businessAreas?: string }) => void;
  disabled?: boolean;
  quotedMessage?: string | null;
  onClearQuote?: () => void;
}

export const ChatInput: React.FC<ChatInputProps> = ({
  onSend,
  disabled,
  quotedMessage,
  onClearQuote
}) => {
  const [message, setMessage] = useState('');
  const [selectedImage, setSelectedImage] = useState<File | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (message.trim() || selectedImage) {
      onSend(message.trim(), selectedImage || undefined);
      setMessage('');
      setSelectedImage(null);
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (message.trim()) {
        onSend(message.trim());
        setMessage('');
      }
    }
  };

  const handleEmojiSelect = (emoji: string) => {
    setMessage(prev => prev + emoji);
  };

  const handleImageSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      setSelectedImage(file);
    }
  };

  const handleLocationClick = async () => {
    if (!navigator.geolocation) {
      alert('您的浏览器不支持地理位置功能');
      return;
    }

    try {
      const position = await new Promise<GeolocationPosition>((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
      });

      const { latitude, longitude } = position.coords;
      const data = await getRegeo({ longitude, latitude });
      
      if (data.status === '1' && data.regeocode) {
        const comp = data.regeocode.addressComponent;
        // businessAreas 拼接
        let business = '';
        if (comp.businessAreas && comp.businessAreas.length > 0) {
          business = comp.businessAreas.map((b: any) => b.name).filter(Boolean).join('、');
        }
        // 展示内容
        const formatted_address = data.regeocode.formatted_address;
        let displayContent = formatted_address;
        if (business) {
          displayContent += `（商圈：${business}）`;
        }
        onSend(displayContent, undefined, {
          latitude,
          longitude,
          address: formatted_address,
          businessAreas: business
        });
      } else {
        throw new Error('获取地址信息失败');
      }
    } catch (error) {
      alert('获取位置信息失败，请检查位置权限设置');
    }
  };

  return (
    <Box sx={{ p: 2, borderTop: 1, borderColor: 'divider' }}>
      {quotedMessage && (
        <Paper
          sx={{
            mb: 1,
            p: 1,
            backgroundColor: 'grey.100',
            display: 'flex',
            alignItems: 'center',
            gap: 1
          }}
        >
          <Box
            sx={{
              flex: 1,
              borderLeft: '3px solid',
              borderColor: 'primary.main',
              pl: 1,
              py: 0.5,
              fontSize: '0.9rem',
              color: 'text.secondary',
            }}
          >
            {quotedMessage}
          </Box>
          <IconButton size="small" onClick={onClearQuote}>
            <Close fontSize="small" />
          </IconButton>
        </Paper>
      )}
      
      {selectedImage && (
        <Box sx={{ mb: 1 }}>
          <img 
            src={URL.createObjectURL(selectedImage)} 
            alt="预览" 
            style={{ maxHeight: 100, borderRadius: 4 }}
          />
        </Box>
      )}
      <form onSubmit={handleSubmit}>
        <Box sx={{ display: 'flex', gap: 1, alignItems: 'center' }}>
          <input
            type="file"
            accept="image/*"
            hidden
            ref={fileInputRef}
            onChange={handleImageSelect}
          />
          <IconButton 
            color="primary" 
            onClick={() => fileInputRef.current?.click()}
          >
            <ImageIcon />
          </IconButton>
          <IconButton 
            color="primary" 
            onClick={handleLocationClick}
            disabled={disabled}
          >
            <LocationOn />
          </IconButton>
          <TextField
            fullWidth
            value={message}
            onChange={(e) => setMessage(e.target.value)}
            onKeyPress={handleKeyPress}
            placeholder="输入消息..."
            disabled={disabled}
            size="small"
            multiline
            maxRows={4}
            sx={{ flex: 1 }}
          />
          <EmojiPickerComponent onSelect={handleEmojiSelect} />
          <IconButton 
            type="submit" 
            color="primary" 
            disabled={disabled || (!message.trim() && !selectedImage)}
          >
            <Send />
          </IconButton>
        </Box>
      </form>
    </Box>
  );
};